package com.dubito.dose.feature.home.viewmodel

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dubito.dose.feature.home.usecase.GetMedicationsUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

/**
 * author: LiLiang
 * createTime: 2022/9/13-16:29
 * remark:
 **/

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val getMedicationsUseCase: GetMedicationsUseCase
) : ViewModel() {

    var state by mutableStateOf(HomeState())
        private set

    init {
        loadMedications()
    }

    fun getUsername() {
        state = state.copy(username = "王大锤")
        // 从数据库获取用户名称
    }

    fun getGreeting() {
        state = state.copy(greeting = "Greeting")
    }

    private fun loadMedications() {
        viewModelScope.launch {
            getMedicationsUseCase.getMedications().onEach {
                state = state.copy(medications = it)
            }.launchIn(viewModelScope)
        }
    }
}